$(function () {
    initTree();
    initTableData(1);

    $("#BtnAdd").bind('click', addUser);

    $("#BtnUpdate").bind('click',updateUser);

    $('#BtnDel').bind('click',deletUser);

});

//user域的全局变量机构id
var unit_Id = "";

function initTree() {
var ztree;
    var setting = {
        async: {
            enable: true,
            url: base + "/private/sys/unit/tree",
            autoParam: ["id"]
        }
        ,view: {
            nameIsHTML: true
        }
        ,data: {
            simpleData: {
                enable: true
            }
        }
    };
    return ztree = $.fn.zTree.init($("#treeDemo"), setting);
}



//添加用户与机构关联同时定义用户角色
var addUser = function () {
        if(unit_Id==null || unit_Id=="" || unit_Id==undefined){
            layer.msg("请选择机构！", {
                time: 1000, //1s后自动关闭
            });
            return;
        }
        layui.use(['form', 'laytpl', 'laydate', 'laypage', 'layer'], function () {
            form = layui.form()
                ,laytpl = layui.laytpl
                ,layer = layui.layer;
            layerAddOpen("userAddForm","新增用户信息",contentAddDiv(unit_Id));
            initSwitch(true);
        });
}



var layerAddOpen=function(id,title,content){
    layer.open({
        id:id
        ,type:1
        , title: title
        , content: content
        , area: ['800px', '650px']
        , btn: ['确认', '取消']
        , yes: function (index, layero) { //确认
            var data = $(layero).find("form").serializeJSON();
            //开关设置值
            if(data.state==null || data.state==undefined){
                data.state=1;
            }
            if(data.state=="on"){
                data.state=0;
            }

                //提交用户验证
                var obj_login = $("input[name='loginname']");
                if(data.loginname == ""){
                    //var obj = $("input[name='loginname']");
                    obj_login.focus();
                    layer.tips('请填写此字段!', obj_login);
                    return false;
                }

                if(data.realname == ""){
                    var obj = $("input[name='realname']");
                    obj.focus();
                    layer.tips('请填写此字段!', obj);
                    return false;
                }

                var pass = $("input[name='password']");
                var passcon = $("input[name='passwordConfirm']");
                if(data.password == ""){
                    pass.focus();
                    layer.tips('请填写密码!', pass);
                    return false;
                }
                if(data.passwordConfirm == ""){
                    passcon.focus();
                    layer.tips('请确认密码!', passcon);
                    return false;
                }

                if(data.password !=  data.passwordConfirm){
                    layer.tips('两次的输入密码不一样,请重新填写!', passcon);
                    pass.val("");
                    passcon.val("");
                    pass.focus();
                    return false;
                }

            if(data.loginname != ""){
                $.ajax({
                    type: "get",
                    url: base + "/private/sys/user/ajaxname?loginname=" + data.loginname,
                    async:false,
                    success: function (isTrue) {
                        if (isTrue =="true") {
                            obj_login.focus();
                            layer.tips('用户名已经存在!', obj_login);
                            return false;
                        } else{
                            $.ajax({
                                url: base + "/private/sys/user/add" ,
                                type:"POST",
                                data: data,
                                success: function (res) {
                                    layer.msg("用户信息已添加成功！", {
                                        time: 1000, //1s后自动关闭
                                    });
                                    layer.close(index);
                                    view(unit_Id);
                                },
                                fail: function (res) {
                                    layer.msg('系统错误！', {
                                        icon: 5
                                    });
                                }
                            });
                        }
                    }
                });
            }

        },success:function () {
            //  bindDataToUpdateForm(data);
        }
    });
}


var contentAddDiv=function (obj) {
    var content;
    var data = {
        "title": {
            "id":"用户编号",
            "loginname":"用户名",
            "realname":"姓名",
            "unitid":"机构编号",
            "password":"密码",
            "passwordConfirm":"确认密码",
            "descript":"描述",
            "position":"职务",
            "address":"地址",
            "telephone":"电话",
            "mobile":"手机",
            "email":"邮箱",
            "linkqq":"QQ号码",
            "linkweb":"个人主页",
            "state":"激活状态"
        }, "text": {
            "id":"",
            "loginname":"",
            "realname":"",
            "unitid":obj||"",
            "password":"",
            "passwordConfirm":"",
            "descript":"",
            "position":"",
            "address":"",
            "telephone":"",
            "mobile":"",
            "email":"",
            "linkqq":"",
            "linkweb":"",
            "state":""
        }, "input": {
            "id":"hidden",
            "loginname":"text",
            "realname":"text",
            "unitid":"text",
            "password":"password",
            "passwordConfirm":"password",
            "descript":"text",
            "position":"text",
            "address":"text",
            "telephone":"text",
            "mobile":"text",
            "email":"text",
            "linkqq":"text",
            "linkweb":"text",
            "state":"switch"
        }, "input_init": {}
    };
    var getDiv = "";
    if(dc_update.length>1){
        getDiv = dc_update[0].innerHTML;
    }else{
        getDiv = dc_update.innerHTML;
    }
    laytpl(getDiv).render(data, function (html) {
        content = html;
    });
    return content;
}


var contentEditDiv=function (obj) {
    var content;
    var data = {
        "title": {
            "id":"用户编号",
            "loginname":"用户名",
            "realname":"姓名",
            "unitid":"机构编号",
            "password":"密码",
            "passwordConfirm":"确认密码",
            "descript":"描述",
            "position":"职务",
            "address":"地址",
            "telephone":"电话",
            "mobile":"手机",
            "email":"邮箱",
            "linkqq":"QQ号码",
            "linkweb":"个人主页",
            "state":"激活状态"
        }, "text": {
            "id":"",
            "loginname":"",
            "realname":"",
            "unitid":obj||"",
            "password":"",
            "passwordConfirm":"",
            "descript":"",
            "position":"",
            "address":"",
            "telephone":"",
            "mobile":"",
            "email":"",
            "linkqq":"",
            "linkweb":"",
            "state":""
        }, "input": {
            "id":"hidden",
            "loginname":"textnotip",
            "realname":"textnotip",
            "unitid":"textnotip",
            "password":"password",
            "passwordConfirm":"password",
            "descript":"textnotip",
            "position":"textnotip",
            "address":"textnotip",
            "telephone":"textnotip",
            "mobile":"textnotip",
            "email":"textnotip",
            "linkqq":"textnotip",
            "linkweb":"textnotip",
            "state":"switch"
        }, "input_init": {}
    };
    var getDiv = "";
    if(dc_update.length>1){
        getDiv = dc_update[0].innerHTML;
    }else{
        getDiv = dc_update.innerHTML;
    }
    laytpl(getDiv).render(data, function (html) {
        content = html;
    });
    return content;
}

var initSwitch = function(flag){
    var html = '';
    if(flag=="true"){
        html += '<input name="state" lay-skin="switch" lay-filter="switch" lay-text="启用|禁用" type="checkbox" > ';
    }else{
        html += '<input checked="" name="state" lay-skin="switch" lay-filter="switch" lay-text="启用|禁用" type="checkbox" > ';
    }
    $("#switch").html(html);
    form.render();
}



var updateUser = function () {
    if(unit_Id==null || unit_Id=="" || unit_Id==undefined){
        layer.msg("请选择机构！", {
            time: 1000, //1s后自动关闭
        });
        return;
    }

    var ids = getCheckedJson("userlist");
    if(ids.length<=0){
        layer.msg("请选择需要编辑的用户！", {
            time: 1000, //1s后自动关闭
        });
        return;
    }
    //获得需要编辑的用户信息ids{}

    layui.use(['form', 'laytpl', 'laydate', 'laypage', 'layer'], function () {
        form = layui.form()
            ,laytpl = layui.laytpl
            ,layer = layui.layer;
        layerEditOpen("userEditForm","编辑用户信息",contentEditDiv(unit_Id),ids);
        initSwitch(true);
    });
}

var layerEditOpen = function (id,title,content,ids) {
    layer.open({
        id:id
        ,type:1
        , title: title
        , content: content
        , area: ['800px', '600px']
        , btn: ['确认', '取消']
        , yes: function (index, layero) { //确认
            var data = $(layero).find("form").serializeJSON();
            //开关设置值
            if(data.state==null || data.state==undefined){
                data[state]=1;
            }
            if(data.state=="on"){
                data.state=0;
            }

            //提交用户验证
            var obj_login = $("input[name='loginname']");
            if(data.loginname == ""){
                //var obj = $("input[name='loginname']");
                obj_login.focus();
                layer.tips('请填写此字段!', obj_login);
                return false;
            }

            if(data.realname == ""){
                var obj = $("input[name='realname']");
                obj.focus();
                layer.tips('请填写此字段!', obj);
                return false;
            }

            var pass = $("input[name='password']");
            var passcon = $("input[name='passwordConfirm']");
            if(data.password == ""){
                pass.focus();
                layer.tips('请填写密码!', pass);
                return false;
            }
            if(data.passwordConfirm == ""){
                passcon.focus();
                layer.tips('请确认密码!', passcon);
                return false;
            }

            if(data.password !=  data.passwordConfirm){
                layer.tips('两次的输入密码不一样,请重新填写!', passcon);
                pass.val("");
                passcon.val("");
                pass.focus();
                return false;
            }

            $.ajax({
                url: base + "/private/sys/user/updateSingle"+"?oldloginname="+ids[0].loginname ,
                type:"POST",
                data: data,
                success: function (res) {
                    layer.msg("用户信息已更新成功！", {
                        time: 1000, //1s后自动关闭
                    });
                    layer.close(index);
                    view(unit_Id);
                   //$(".layui-laypage-curr > em:nth-child(2)").value();
                },
                fail: function (res) {
                    layer.msg('系统错误！', {
                        icon: 5
                    });
                }
            });
        },success:function () {
            bindDataToUpdateForm(ids[0]);
        }
    });
}

var bindDataToUpdateForm=function(data){
    //alert(JSON.stringify(data))
    $("input[name='id']").val(data.id);
    $("input[name='loginname']").val(data.loginname);
    $("input[name='realname']").val(data.realname);
    $("input[name='unitid']").val(data.unitid);
    $("input[name='password']").val(data.password);
    $("input[name='passwordConfirm']").val(data.password);
    $("input[name='descript']").val(data.descript);
    $("input[name='position']").val(data.position);
    $("input[name='address']").val(data.address);
    $("input[name='telephone']").val(data.telephone);
    $("input[name='mobile']").val(data.mobile);
    $("input[name='email']").val(data.email);
    $("input[name='linkqq']").val(data.linkqq);
    $("input[name='linkweb']").val(data.linkweb);
    $("input[name='state']").val(data.state);
}

var deletUser = function(){
    if(unit_Id==null || unit_Id=="" || unit_Id==undefined){
        layer.msg("请选择机构！", {
            time: 1000, //1s后自动关闭
        });
        return;
    }
    var ids = getCheckedJson("userlist");
    var deletes_ids =[];
    if(ids.length<=0){
        layer.msg("请选择需要删除的用户！", {
            time: 1000, //1s后自动关闭
        });
        return;
    }else{
        $.each(ids,function (index, item) {
            deletes_ids.push(item.id);
        })
    }

    // alert(JSON.stringify(deletes_ids));

    layer.confirm('删除用户,该用户所属的角色会被一起删除，您确认要删除吗？', {
        btn: ['删除','取消'] //按钮
    }, function(index,layero){
        $.ajax({
            url: base + "/private/sys/user/delete",
            data: {ids:deletes_ids.toString()},
            type: "POST",
            async: false,
            success: function (res) {
                layer.msg('已成功删除！', {
                    time: 1000, //20s后自动关闭
                });
                initTableData(1);
            },
            fail: function (res) {
                layer.msg('系统错误！', {
                    icon: 5
                });
            }
        });
    });

}


var initTableData = function(num){
    var param = {
        unitId:unit_Id,
        page_num:num,
        page_size:"10"
    }
    $.ajax({
        url: base + "/private/sys/user/listUserByUnitId",
        data: param,
        type:"post",
        success: function (data, textStatus, jqXHR) {
            //alert(JSON.stringify(data));
            data=JSON.parse(data);
            var pageCount = data.pageCount;
            var dataObj ={
                "list":data.rows,
                "dataTool":{
                    "title":{
                        "loginname": "用户名"
                        ,"realname": "姓名"
                        ,"state":"帐户状态"
                        ,"position":"职务"
                        ,"email":"电子邮件"
                        ,"telephone":"固定电话"
                        ,"mobile":"手机号码"
                    },
                    "titleCheckbox":true,
                    "noDataStatus":true
                }
            };

            showPageTable('userlist', dataObj,num,pageCount,"initTableData");
        },
        error: function () {
        }
    });
}


var view=function(unitId){
    //此处初始化机构id方便表格查询显示
    unit_Id=unitId;
    initTableData(1);
}


